
import requests
import json
import urllib.parse
from util.jsonTool import *
class ApiClient(object):
    def __init__(self,engineCode,engineSecret):
        self.__baseUrl='https://www.h3yun.com'
        self.__invokeUrl='OpenApi/Invoke'
        self.__downloadUrl='Api/DownloadBizObjectFile'
        self.__uploadUrl='OpenApi/UploadAttachment'
        self.__engineCode=engineCode
        self.__engineSecret=engineSecret
    
    # 基础post请求
    def _postBase_customizeapi(self,controller,actionName,appCode,body):
        body["Controller"]=controller
        body["ActionName"]=actionName
        body["AppCode"]=appCode
        payload=json_serialize(body)
        headers = {
          'EngineCode': self.__engineCode,
          'EngineSecret': self.__engineSecret,
          'Content-Type': 'application/json'
        } 
        url=self.__baseUrl+"/"+self.__invokeUrl
        response=requests.request("POST",url,headers=headers,data=payload)
        return response

    # 基础post请求       
    def _postBase_standardapi(self,schemaCode,actionName,body):
        body["SchemaCode"]=schemaCode
        body["ActionName"]=actionName
        payload=json_serialize(body)
        headers = {
          'EngineCode': self.__engineCode,
          'EngineSecret': self.__engineSecret,
          'Content-Type': 'application/json'
        } 
        url=self.__baseUrl+"/"+self.__invokeUrl
        response=requests.request("POST",url,headers=headers,data=payload)
        return response
    
    # 基础post请求       
    def _postBase_fileapi(self,params):
        params["EngineCode"]=self.__engineCode
        headers = {
          'EngineCode': self.__engineCode,
          'EngineSecret': self.__engineSecret,
          'Content-Type': 'application/json'
        } 
        url=self.__baseUrl+"/"+self.__downloadUrl
        response=requests.post(url,headers=headers,params=params)
        return response
    # post请求，接收controller参数，请求氚云自定义http接口  
    def postResponse_customizeapi(self,controller,actionName,appCode,body):
        response=self._postBase_customizeapi(controller,actionName,appCode,body)
        result=json.loads(response.text)     
        return result
    
    # post请求，请求氚云标准接口
    def postResponse_standardapi(self,schemaCode,actionName,body):
        response=self._postBase_standardapi(schemaCode,actionName,body)
        result=json.loads(response.text)     
        return result
    
    def postReponseForUpload(self,files,params):
        headers={
            "EngineCode":self.__engineCode,
            "EngineSecret":self.__engineSecret
        }
        url=self.__baseUrl+"/"+self.__uploadUrl
        response=requests.post(url,headers=headers,files=files,params=params)
        return response

    
    # 查询业务对象
    def loadBizObject(self,schemaCode,objectId):
        body={"BizObjectId":objectId}
        result=self.postResponse_standardapi(schemaCode,"LoadBizObject",body)
        if result["ReturnData"]!=None:
            return result["ReturnData"]["BizObject"]
        return None
    
    # 批量查询业务对象
    def loadBizObjects(self,schemaCode,filter):
        body={"Filter":json_serialize(filter)}
        result=self.postResponse_standardapi(schemaCode,"LoadBizObjects",body)
        if result["ReturnData"]!=None:
            return result["ReturnData"]["BizObjectArray"]
        return None  

    # 创建业务对象
    def createBizObject(self,schemaCode,isSubmit,bizObject):
        body={
            "IsSubmit":isSubmit,
            "BizObject":json_serialize(bizObject)
        }      
        result=self.postResponse_standardapi(schemaCode,"CreateBizObject",body)
        if result["ReturnData"]!=None:
            return result["ReturnData"]["BizObjectId"]
        return None 

    # 批量创建业务对象
    def createBizObjects(self,schemaCode,isSubmit,bizObjects):
        body={
            "IsSubmit":isSubmit,
            "BizObjectArray":self.__bizObjectListToStrList(bizObjects)
        }      
        result=self.postResponse_standardapi(schemaCode,"CreateBizObjects",body)
        if result["ReturnData"]!=None:
            return result["ReturnData"]["BizObjectIdArray"]
        return None 
    
    # 更新业务对象
    def updateBizObject(self,schemaCode,objectId,bizObject):
        body={
            "BizObjectId":objectId,
            "BizObject":json_serialize(bizObject)
        }      
        result=self.postResponse_standardapi(schemaCode,"UpdateBizObject",body)

    # 删除业务对象
    def removeBizObject(self,schemaCode,objectId):
        body={
            "BizObjectId":objectId
        }
        result=self.postResponse_standardapi(schemaCode,"RemoveBizObject",body)

    # 下载附件
    def downloadBizObjectFile(self,schemaCode,objectId,bizProperties,fieldName,attachmentId):
        params={
            "attachmentId":attachmentId
        }
        result=self._postBase_fileapi(params)
        headerContents=result.headers.get("Content-Disposition")
        if len(headerContents)>0:
            contentName=headerContents
            fileName=urllib.parse.unquote(contentName.split(';')[1].split('=')[1])
            contentType=result.headers.get("Content-Type")
            file={
                "fileId":attachmentId,
                "fileName":fileName,
                "fileContent":result.content,
                "contentType":contentType,
                "schemaCode":schemaCode,
                "bizObjectId":objectId,
                "bizProperties":bizProperties
            }
            return file
        return None

    # 上传文件
    def uploadBizObjectFile(self,schemaCode,objectId,fieldName,files):
        params={
            "SchemaCode":schemaCode,
            "FilePropertyName":fieldName,
            "BizObjectId":objectId
        }
        result=self.postReponseForUpload(files,params)
        return result["ReturnData"]["AttachmentId"]

    # post请求数据
    def post(self,controller,actionName,appCode,body):
        result=self.postResponse_customizeapi(controller,actionName,appCode,body)
        return result["ReturnData"]

    def __bizObjectListToStrList(self,bizObjects):
        result=[]
        for obj in bizObjects:
            result.append(json_serialize(obj)) 
        return result                      
              